#!/usr/bin/env zsh

'builtin' 'emulate' '-L' 'zsh' '-o' 'no_aliases' '-o' 'err_return' || 'builtin' 'exit'
setopt no_unset extended_glob typeset_silent no_multi_byte \
       prompt_percent no_prompt_subst warn_create_global pipe_fail

() {

if [[ ${ZSH_VERSION-} != (5.<8->*|<6->.*) ]]; then
  print -ru2 -- "${ZSH_SCRIPT:t}: zsh >= 5.8 is required to execute this script"
  return 1
fi

local -r root_dir=${ZSH_SCRIPT:A:h}

zmodload zsh/zutil zsh/system zsh/zselect

local -a help privileged git config_dir=(--config-dir $root_dir/configs)

if [[ -r /proc/1/cpuset(#qN-.) &&
      "$(</proc/1/cpuset)" == /docker/[[:xdigit:]](#c64) ]]; then
  local -a isolation=(--isolation user)
  local -ri in_docker=1
else
  local -a isolation=(--isolation docker)
  local -ri in_docker=0
fi

zparseopts -D -K -F --        \
  {h,-help}=help              \
  {p,-privileged}=privileged  \
  {I,-isolation}:=isolation   \
  {c,-config-dir}:=config_dir \
  {g,-git}:=git

if (( $#help )); then
  print -r -- "usage: ${ZSH_SCRIPT:t} [OPTION].. CONFIG"
  print -r --
  print -r -- 'OPTIONS'
  print -r -- '  -h,--help'
  print -r -- '  -p,--privileged'
  print -r -- '  -I,--isolation <docker|user>'
  print -r -- '  -g,--git <yes|no|empty> [default=no]'
  return
fi

if [[ ! -d $config_dir[2] ]]; then
  print -ru2 -- "${ZSH_SCRIPT:t}: directory does not exist: ${(q-)config_dir[2]}"
  return 1
fi

if [[ $isolation[2] != (docker|user) ]]; then
  print -ru2 -- "${ZSH_SCRIPT:t}: invalid value of --isolation: ${(q-)isolation[2]}"
  return 1
fi

if (( ARGC > 1 )); then
  print -ru2 -- "${ZSH_SCRIPT:t}: too many positional arguments"
  return 1
fi

if (( ARGC )); then
  local -r cfg=$1

  if [[ -z $cfg || $cfg == */* ]]; then
    print -ru2 -- "${ZSH_SCRIPT:t}: invalid config name: ${(q-)cfg}"
    return 1
  fi
  if [[ ! -e $config_dir[2]/$cfg ]]; then
    print -ru2 -- "${ZSH_SCRIPT:t}: directory does not exist: $config_dir[2]/$cfg"
    return 1
  fi
  if [[ ! -e $config_dir[2]/$cfg/setup ]]; then
    print -ru2 -- "${ZSH_SCRIPT:t}: file does not exist: $config_dir[2]/$cfg/setup"
    return 1
  fi
  if [[ ! -f $config_dir[2]/$cfg/setup || ! -x $config_dir[2]/$cfg/setup ]]; then
    print -ru2 -- "${ZSH_SCRIPT:t}: not an executable file: $config_dir[2]/$cfg/setup"
    return 1
  fi
else
  local -r cfg=
fi

if [[ ! -t 0 || ! -t 1 || ! -t 2 ]]; then
  print -ru2 -- "${ZSH_SCRIPT:t}: all standard file descriptors must be TTY"
  return 1
fi

if [[ $isolation[2] == user ]]; then
  if (( EUID )); then
    if (( in_docker )); then
      print -ru2 -- "${ZSH_SCRIPT:t}: you must be root for --isolation user"
    else
      print -ru2 -- "${ZSH_SCRIPT:t}: you must be root for --isolation user; try with sudo"
    fi
    return 1
  fi
  local create_repo=()
  if (( $#git )); then
    if [[ $git[2] != (yes|no|empty) ]]; then
      print -ru2 -- "${ZSH_SCRIPT:t}: invalid value of --git: ${(q-)git[2]}"
      return 1
    fi
    if [[ $git[2] != no ]]; then
      create_repo=('~/zsh-bench/internal/create-repo ~/repo '${(q-)git[2]} 'cd ~/repo')
    fi
  fi
  exec -- $root_dir/internal/install-config \
    'zsh-playground' $#privileged $config_dir[2] "$cfg" $create_repo 'exec zsh -l'
  return
fi

[[ $isolation[2] == docker ]]

() {
  local cmd
  for cmd in docker tar; do
    if [[ ! -v commands[$cmd] ]]; then
      print -ru2 -- "${ZSH_SCRIPT:t}: command not found: ${(q-)cmd}"
      return 1
    fi
  done
}

local -r img=ubuntu:22.04

function docker-run() {
  local flags=(-i --rm --init -e TERM -e COLORTERM -e LC_ALL=C.UTF-8 -w /root)
  if (( $#privileged )); then
    flags+=(--privileged -v /:/host)
  fi
  DOCKER_CONTENT_TRUST=1 command docker run $flags -- $img sh -uec "$1"
}

if ! docker-run true; then
  print -ru2 -- "${ZSH_SCRIPT:t}: cannot run docker; try with sudo?"
  return 1
fi

local self configs= minimal=
self=${"$(cd -q -- $root_dir && command tar -cz -- ^(.git|configs) && print -n x)"[1,-2]}
() {
  (( $# )) || set -- $config_dir[2]/*(ND:t)
  (( $# )) || return 0
  configs=${"$(cd -q -- $config_dir[2] && command tar -cz -- $@ && print -n x)"[1,-2]}
} $cfg
if [[ ! -e $root_dir/internal/minimal ]]; then
  minimal=${"$(cd -q -- $root_dir/configs && command tar -cz -- minimal && print -n x)"[1,-2]}
fi

print -r -- "==> starting $img in docker ..."

local setup=(
  'cpuset="$(cat /proc/1/cpuset)"'
  '[ -n "$cpuset" ]'
  'printf "==> docker container ID: %.12s\\n" "${cpuset##*/}" >&2'
  'mkdir ~/zsh-bench'
  'cd ~/zsh-bench'
  'head -c '$#self' | tar -xzm'
  'mkdir configs'
  'cd configs'
  ${configs:+'head -c '$#configs' | tar -xzm'}
  'cd ../internal'
  ${minimal:+'head -c '$#minimal' | tar -xzm'}
  'cd /'
  '( ( cat <&3 >/dev/null || true; /bin/kill -TERM -- -$$; ) & ) 3<&0'
  '~/zsh-bench/internal/install-deps >&2'
  'zsh="$(which zsh)"'
  'chsh -s "$zsh"'
  '~/zsh-bench/internal/minimal/setup'
  'printf "%s\\n" "$cpuset"'
  'cat >/dev/null')

if [[ -n $cfg ]]; then
  local -a create_repo=()
  if (( $#git )); then
    if [[ $git[2] != (yes|no|empty) ]]; then
      print -ru2 -- "${ZSH_SCRIPT:t}: invalid value of --git: ${(q-)git[2]}"
      return 1
    fi
    if [[ $git[2] != no ]]; then
      create_repo=(
        '~/zsh-bench/internal/create-repo ~/repo '${(q-)git[2]}
        'cd ~/repo')
    fi
  fi
  local login=(
    'exec'
    '~/zsh-bench/internal/install-config'
    'zsh-playground'
    $#privileged
    '~/zsh-bench/configs'
    ${(qqq)cfg}
    ${(@qqq)create_repo}
    '"exec zsh -l"')
else
  if (( $#git )); then
    print -ru2 -- "${ZSH_SCRIPT:t}: --git is incompatible with --isolation user and positional arguments"
    return 1
  fi
  local cmds=('cd' 'SHELL=/usr/bin/zsh PATH="$PATH:$HOME/zsh-bench" exec zsh -l')
  local login=(${(j: && :)cmds})
fi

local tty
exec {tty}<&0

{
  exec {tty}<&-
  print -r -- $sysparams[pid]
  print -rn -- $self
  print -rn -- $configs
  print -rn -- $minimal
  trap 'exit 0' TERM PIPE
  while true; do
    zselect -t 360000 || true
    print 2>/dev/null || exit 0
  done
} | {
  exec {tty}<&-
  local pid
  IFS= read -r pid
  print -r -- $pid
  docker-run ${(j: && :)setup}
} | {
  local pid
  IFS= read -r pid
  {
    local cpuset
    IFS= read -r cpuset
    exec 0<&$tty {tty}<&-
    if [[ $cpuset != /docker/[[:xdigit:]]## ]]; then
      print -ru2 -- "${ZSH_SCRIPT:t}: unexpected content of /proc/1/cpuset in the docker container"
      return 1
    fi
    local ret
    command docker exec -e TERM -e COLORTERM -e LC_ALL=C.UTF-8 -it -- \
      ${cpuset:t} sh -c ${(j: :)login} || ret=$?
    return ret
  } always {
    kill -- $pid 2>/dev/null || true
  }
}

} "$@"
